<script setup>
import { onMounted, ref, watch } from 'vue'
import {
  deleteTestRequestApi,
  exportCategoryDataApi,
  getTestRequestListApi,
  saveTestRequestApi,
  updateStatusByIdApi,
  updateTestRequestApi
} from '@/api/testRequest.js'
import { getProjectListApi } from '@/api/project.js'
import { getVersionListApi } from '@/api/version.js'
import { ElMessage } from 'element-plus'
import { getUsersByRoleIdApi } from '@/api/sysUser.js'
import { useUserStore } from '@/stores/index.js'
import { formatDate } from '@/utils/dateUtils.js'

const userStore = useUserStore()
const user = userStore.user

//基础数据构
const defaultForm = {
  projectId: '',
  projectName: '',
  versionNumber: '',
  requestName: '',
  plannedTestTime: '',
  actualTestTime: null,
  smokeTestPlanUrl: '',
  description: '',
  status: 1,
  testFailedNumber: 0,
  isPostpone: false,
  postponeTime: '',
  createdBy: 0,
  developers: [],
  testers: [],
  id: '',
  createTime: '',
  updateTime: ''
}

// 定义 testRequest 为响应式对象
const testRequest = ref({ ...defaultForm })

// 定义保留字段
const fieldsToKeep = ['projectId', 'projectName', 'versionNumber']

// 定义重置函数
function resetForm() {
  const newForm = { ...defaultForm }

  Object.keys(newForm).forEach((key) => {
    if (!fieldsToKeep.includes(key)) {
      testRequest.value[key] = newForm[key]
      console.log('key ==' + key + '  value' + testRequest.value[key])
    }
  })
}
const defaultFormDto = {
  requestId: 0,
  status: 0
}

const testRequestDto = ref(defaultFormDto)

// 列表
const list = ref([])
//分页
const total = ref(0)
const pageParams = ref({
  page: 1,
  limit: 10
})
const queryDto = ref({
  projectId: '',
  versionNumber: ''
})

// 查询列表接口
const fetchData = async () => {
  queryDto.value.projectId = testRequest.value.projectId
  queryDto.value.versionNumber = testRequest.value.versionNumber
  const response = await getTestRequestListApi(
    pageParams.value.page,
    pageParams.value.limit,
    queryDto.value
  )
  total.value = response.data.total
  list.value = response.data.records
}
onMounted(() => {
  fetchProjectOptions()
  fetchVersionForProjectOptions()
})

//监听切换所属项目
watch(
  () => testRequest.value.projectId,
  (newId, oldId) => {
    console.log('项目 ID 变化:', oldId, '->', newId)
    fetchVersionForProjectOptions()
  }
)
//监听切换所属版本
watch(
  () => testRequest.value.versionNumber,
  (newVersionNumber, oleVersionNumber) => {
    console.log('项目version变化：', newVersionNumber, oleVersionNumber)
    fetchData()
  }
)
// 新增
const dialogVisible = ref(false)
const addShow = () => {
  dialogVisible.value = true
  getUserListByRole()
}

const form = ref()
const submit = async () => {
  // 触发表单校验
  await form.value.validate()
  // 如果表单校验通过，执行提交逻辑
  if (!testRequest.value.id) {
    testRequest.value.createdBy = user.id
    // testRequest.value.developers = devUserList
    // testRequest.value.testers = qaUserList
    await saveTestRequestApi(testRequest.value)
    resetForm()
    ElMessage.success('新增成功')
    devUserList.value = []
    qaUserList.value = []
    fetchData()
    dialogVisible.value = false
  } else {
    await updateTestRequestApi(testRequest.value)
    resetForm()
    ElMessage.success('编辑成功')
    dialogVisible.value = false
    devUserList.value = []
    qaUserList.value = []
    fetchData()
  }
}

//项目列表
const projectOptions = ref([])
//拿到项目列表
const fetchProjectOptions = async () => {
  const response = await getProjectListApi(1, 1000, null)
  projectOptions.value = response.data.records
  //判断当projectOptions不为空时，默认选择第一
  testRequest.value.projectName = projectOptions.value[0].projectName
  testRequest.value.projectId = projectOptions.value[0].id
}
//当更改项目名称后同步更新项目id
const handleChange = (item) => {
  testRequest.value.projectId = item.id
}

// 选择项目选择所属版本
const versionNumOptions = ref([])

const fetchVersionForProjectOptions = async () => {
  const response = await getVersionListApi(1, 10000, null)
  const versionLists = response.data.records
  console.log('versionLists', versionLists)
  versionNumOptions.value = versionLists.filter((item) => {
    return testRequest.value.projectId === item.projectId
  })
  testRequest.value.versionNumber = versionNumOptions.value[0].versionNumber
}

// 定义所属开发人员和测试人员
const allDevUserList = ref([])
const allQaUserList = ref([])
const devUserList = ref([])
const qaUserList = ref([])

const getUserListByRole = async () => {
  const response = await getUsersByRoleIdApi('DEV')
  allDevUserList.value = response.data

  const { data } = await getUsersByRoleIdApi('QA')
  allQaUserList.value = data
}

/**
 * 编辑
 */

const editShow = (row) => {
  testRequest.value = { ...row }
  getUserListByRole()
  console.log('devusers ===' + testRequest.value.developers)
  devUserList.value = testRequest.value.developers
  qaUserList.value = testRequest.value.testers
  dialogVisible.value = true
}

/*
删除
 */
const deleteTestRequest = async (row) => {
  await deleteTestRequestApi(row.id)
  ElMessage.success('删除成功')
  fetchData()
}

const getStatusText = (status) => {
  const statusMap = {
    1: '待提测',
    2: '已提测',
    3: '提测未通过',
    4: '提测通过'
  }
  return statusMap[status] || '未知状态' // 返回未知状态以防止不在枚举范围内的值
}

//触发提测操作
const submitTest = async (row) => {
  // 提测通过操作逻辑
  testRequestDto.value.requestId = row.id
  testRequestDto.value.status = 2
  await updateStatusByIdApi(testRequestDto.value)
  testRequestDto.value = { ...defaultFormDto }
  fetchData()
  ElMessage.success('提测成功，待测试人员进行冒烟验收')
  console.log('提测成功', row)
}
const approveTest = async (row) => {
  // 提测通过操作逻辑
  testRequestDto.value.requestId = row.id
  testRequestDto.value.status = 4
  await updateStatusByIdApi(testRequestDto.value)
  testRequestDto.value = { ...defaultFormDto }
  fetchData()
  ElMessage.success('冒烟验收通过')
}

const rejectTest = async (row) => {
  // 提测通过操作逻辑
  testRequestDto.value.requestId = row.id
  testRequestDto.value.status = 3
  await updateStatusByIdApi(testRequestDto.value)
  testRequestDto.value = { ...defaultFormDto }
  fetchData()
  ElMessage.success('提测被驳回')
  // 提测驳回操作逻辑
  console.log('提测驳回', row)
}
// 格式化函数
const dateFormatter = (row, column, cellValue) => {
  return formatDate(cellValue)
}

const exportData = () => {
  // 调用 ExportCategoryData() 方法获取导出数据
  exportCategoryDataApi(queryDto.value).then((res) => {
    // 创建 Blob 对象，用于包含二进制数据
    const blob = new Blob([res])
    // 创建 a 标签元素，并将 Blob 对象转换成 URL
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    // 设置下载文件的名称
    link.download = '提测单数据.xlsx'
    // 模拟点击下载链接
    link.click()
  })
}
//   查看详情
const dialogDetailsVisible = ref(false)

const queryTestRequestDetails = (row) => {
  testRequest.value = { ...row }
  getUserListByRole()
  devUserList.value = testRequest.value.developers
  qaUserList.value = testRequest.value.testers
  dialogDetailsVisible.value = true
}

/**
 * 关闭弹窗
 */

const stopDialog = () => {
  dialogVisible.value = false
  dialogDetailsVisible.value = false
  devUserList.value = []
  qaUserList.value = []
  resetForm()
}
</script>

<template>
  <!-- 搜索表单 -->
  <el-form label-width="" size="small">
    <el-row type="flex" gutter="10">
      <el-col :span="6">
        <el-form-item label="所属项目">
          <el-select v-model="testRequest.projectName" placeholder="选择项目">
            <el-option
              v-for="item in projectOptions"
              :key="item.id"
              :label="item.projectName"
              :value="item.projectName"
              @mouseleave="handleChange(item)"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="所属版本">
          <el-select v-model="testRequest.versionNumber" placeholder="所属版本">
            <el-option
              v-for="item in versionNumOptions"
              :key="item.id"
              :label="item.versionNumber"
              :value="item.versionNumber"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-button
          type="primary"
          align="middle"
          size="small"
          @click="searchSysRole"
        >
          搜索
        </el-button>
        <el-button size="small"> 重置 </el-button>
      </el-col>
    </el-row>
  </el-form>
  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow">添 加</el-button>
    <el-button type="success" size="small" @click="exportData">导出</el-button>
  </div>
  <!-- 新增或编辑弹窗-->
  <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
    <el-form :model="testRequest" ref="form" label-width="120px">
      <el-form-item
        label="所属项目"
        prop="projectName"
        :rules="[
          { required: true, message: '请选择所属项目', trigger: 'blur' }
        ]"
      >
        <el-input v-model="testRequest.projectName" disabled />
      </el-form-item>
      <el-form-item
        label="所属版本"
        prop="versionNumber"
        :rules="[
          { required: true, message: '请选择所属版本', trigger: 'blur' }
        ]"
      >
        <el-input v-model="testRequest.versionNumber" disabled />
      </el-form-item>
      <el-form-item
        label="提测需求名称"
        prop="requestName"
        :rules="[
          { required: true, message: '请输入提测需求名称', trigger: 'blur' }
        ]"
      >
        <el-input
          placeholder="建议与版本计划池中保持一致"
          v-model="testRequest.requestName"
        />
      </el-form-item>

      <el-form-item
        label="计划提测时间"
        prop="plannedTestTime"
        :rules="[
          { required: true, message: '请选择计划提测时间', trigger: 'change' }
        ]"
      >
        <el-date-picker
          v-model="testRequest.plannedTestTime"
          type="date"
          placeholder="选择日期"
        />
      </el-form-item>

      <el-form-item
        label="冒烟测试计划"
        prop="smokeTestPlanUrl"
        :rules="[
          {
            required: true,
            message: '请输入ms冒烟测试计划地址',
            trigger: 'blur'
          }
        ]"
      >
        <el-input
          placeholder="请输入ms平台中新建的冒烟测试计划地址"
          v-model="testRequest.smokeTestPlanUrl"
        />
      </el-form-item>

      <el-form-item
        label="所属开发人员"
        prop="developers"
        :rules="[
          { required: true, message: '请选择开发人员', trigger: 'change' }
        ]"
      >
        <el-select
          v-model="testRequest.developers"
          multiple
          placeholder="选择需求负责的开发人员"
          style="width: 240px"
        >
          <el-option
            v-for="item in allDevUserList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        label="所属测试人员"
        prop="testers"
        :rules="[
          { required: true, message: '请选择测试人员', trigger: 'change' }
        ]"
      >
        <el-select
          v-model="testRequest.testers"
          multiple
          placeholder="选择负责需求的测试人员"
          style="width: 240px"
        >
          <el-option
            v-for="item in allQaUserList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="描述" prop="description">
        <el-input
          v-model="testRequest.description"
          type="textarea"
          :rows="4"
          placeholder="请输入描述"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="stopDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
  <!---数据表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column prop="projectName" label="项目名称" />
    <el-table-column prop="versionNumber" label="版本号" />
    <el-table-column prop="requestName" label="提测需求名称" />
    <el-table-column prop="smokeTestPlanUrl" label="ms冒烟测试计划地址" />

    <el-table-column
      prop="plannedTestTime"
      label="计划提测时间"
      :formatter="dateFormatter"
    />
    <el-table-column prop="actualTestTime" label="实际提测时间" />
    <el-table-column prop="isPostpone" label="是否提测延期">
      <template v-slot="scope">
        {{ scope.row.isPostpone ? '是' : '否' }}
      </template>
    </el-table-column>
    <el-table-column prop="testFailedNumber" label="提测失败次数">
    </el-table-column>
    <el-table-column prop="isPostpone" label="状态">
      <template #default="scope">
        <span>
          {{ getStatusText(scope.row.status) }}
        </span>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center" width="280" #default="scope">
      <div>
        <!-- 待提测状态 -->
        <el-button
          v-if="scope.row.status === 1"
          type="primary"
          size="small"
          @click="editShow(scope.row)"
        >
          编辑
        </el-button>
        <el-button
          v-if="scope.row.status === 1"
          type="danger"
          size="small"
          @click="deleteTestRequest(scope.row)"
        >
          删除
        </el-button>
        <el-button
          v-if="scope.row.status === 1"
          type="success"
          size="small"
          @click="submitTest(scope.row)"
        >
          提测
        </el-button>

        <!-- 已提测状态 -->
        <el-button
          v-if="scope.row.status === 2"
          type="success"
          size="small"
          @click="approveTest(scope.row)"
        >
          提测通过
        </el-button>
        <el-button
          v-if="scope.row.status === 2"
          type="danger"
          size="small"
          @click="rejectTest(scope.row)"
        >
          提测驳回
        </el-button>

        <!-- 提测未通过状态 -->
        <el-button
          v-if="scope.row.status === 3"
          type="success"
          size="small"
          @click="submitTest(scope.row)"
        >
          重新提测
        </el-button>

        <!-- 非待提测状态 -->
        <el-button
          v-if="scope.row.status !== 1"
          type="success"
          size="small"
          @click="queryTestRequestDetails(scope.row)"
        >
          详情
        </el-button>
      </div>
    </el-table-column>
  </el-table>
  <el-pagination
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    @size-change="fetchData"
    @current-change="fetchData"
  />

  <!--  详情弹窗-->
  <el-dialog v-model="dialogDetailsVisible" title="详情" width="40%">
    <el-form label-width="120px">
      <el-form-item label="所属项目">
        <el-input v-model="testRequest.projectName" disabled />
      </el-form-item>
      <el-form-item label="所属版本">
        <el-input v-model="testRequest.versionNumber" disabled />
      </el-form-item>
      <el-form-item label="提测需求名称">
        <el-input v-model="testRequest.requestName" disabled></el-input>
      </el-form-item>

      <el-form-item label="计划提测时间" prop="plannedTestTime">
        <el-date-picker
          v-model="testRequest.plannedTestTime"
          type="date"
          placeholder="选择日期"
          disabled
        />
      </el-form-item>
      <el-form-item label="ms冒烟测试计划">
        <el-input disabled v-model="testRequest.smokeTestPlanUrl"></el-input>
      </el-form-item>

      <el-form-item label="所属开发人员">
        <el-select
          v-model="devUserList"
          multiple
          placeholder="选择需求负责的开发人员"
          style="width: 240px"
          disabled
        >
          <el-option
            v-for="item in allDevUserList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
            disabled
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属测试人员">
        <el-select
          v-model="qaUserList"
          multiple
          placeholder="选择负责需求的测试人员"
          style="width: 240px"
          disabled
        >
          <el-option
            v-for="item in allQaUserList"
            :key="item.id"
            :label="item.username"
            :value="item.id"
            disabled
          />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="testRequest.description"
          type="textarea"
          :rows="4"
          placeholder="请输入描述"
          disabled
        />
      </el-form-item>
      <el-form-item class="dialog-footer">
        <el-button type="primary" @click="stopDialog">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
